/*  tBookShelf: SharedPtr
    (C) 2007  TvN (Volodymyr Tarasenko), e-mail: tvntsr@yahoo.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef SHARED_PTR_UTILS_HPP
#define SHARED_PTR_UTILS_HPP

/// This solution is not thread safe, if you need thread safety 
/// take a look at boost::shared_ptr instead

class SharedCounter
{
public:
    SharedCounter(int i = 0)
    {
        counter = new int(i);
    }

    ~SharedCounter()
    {
        if (--(*counter) <= 0)
            delete counter;
    }

    SharedCounter(const SharedCounter& i)
        : counter(i.counter)
    {
        ++(*counter);
    }

    SharedCounter& operator=(const SharedCounter& i)
    {
        this->~SharedCounter();
        new(this) SharedCounter(i);

        return *this;
    }

    int operator()()
    {
        return *counter;
    }

//private:
    int *counter;
};

template<typename T>
class SharedPtr
{
    typedef T value_type;
public:
    explicit 
    SharedPtr(T* i)
        : ptr(i), count(1)
    {    }
    SharedPtr()
        : ptr(0), count(1)
    {
        ptr = new value_type;
    }

    SharedPtr(const SharedPtr& i)
        : ptr(i.ptr), count(i.count)
    {    }

    ~SharedPtr()
    {
        if (count() <= 1)
        {
            delete ptr;
        }
    }

    void reset(T* i)
    {
        this->~SharedPtr();
        new(this) SharedPtr(i);
    }

    SharedPtr& operator=(const SharedPtr& i)
    {
        this->~SharedPtr();

        new(this) SharedPtr(i);

        return *this;
    }
    
    value_type* operator->()
    {
        return ptr;
    }

    value_type& operator*()
    {
        return *ptr;
    }

//    void swap()
private:
    value_type*   ptr;
    SharedCounter count;
};

template<class T, class U>
bool 
operator==(SharedPtr<T> const & a, SharedPtr<U> const & b)
{
    return *a == *b;
}

template<class T, class U>
bool 
operator!=(SharedPtr<T> const & a, SharedPtr<U> const & b)
{
    return *a != *b;
}

template<class T, class U>
bool 
operator<(SharedPtr<T> const & a, SharedPtr<U> const & b)
{
    return *a < *b;
}

// template<class T> 
// void swap(SharedPtr<T> & a, SharedPtr<T> & b); // never throws

template<class E, class T, class Y>
std::basic_ostream<E, T> & 
operator<< (std::basic_ostream<E, T> & os, SharedPtr<Y> const & p)
{
    os << (*p);
    return os;
}


#endif //SHARED_PTR_UTILS_HPP
